package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.cwgl.FpdrDao;
import com.hnkywl.sts.dao.cwgl.pjdr.JxfpdrDao;
import com.hnkywl.sts.dao.cwgl.pjdr.WlfpdrDao;
import com.hnkywl.sts.dao.cwgl.pjdr.XxfpdrDao;
import com.hnkywl.sts.dao.jsgl.FpDao;
import com.hnkywl.sts.dao.jsgl.JsdhbDao;
import com.hnkywl.sts.entity.cggl.Jsd;
import com.hnkywl.sts.entity.cggl.Jsdhb;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.zjgl.Pj;
import com.hnkywl.sts.entity.zjgl.Pjdr;
import com.hnkywl.sts.entity.zjgl.Xyz;
import com.hnkywl.sts.service.jsgl.FpService;
import com.hnkywl.sts.service.jsgl.XsjsdService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.EasyuiAdapter;
import com.hnkywl.sts.util.UUIDGenerator;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-4-30
 * Time: 上午9:58
 * To change this template use File | Settings | File Templates.
 */
@Service
public class FpdrService {
    private XsjsdService jsdService;
    private JsdhbDao jsdhbDao;
    private FpdrDao fpdrDao;
    private FpDao fpDao;
    private JxfpdrDao jxfpdrDao;
    private XxfpdrDao xxfpdrDao;
    private WlfpdrDao wlfpdrDao;

    public Map findVoucherMain(Long jsdId) {
        Jsd jsd = jsdService.findXsjsdDetail(jsdId);
//        Map voucher = null;
//        if(jsd.getType() == 0){
//            voucher = jxfpdrDao.findVoucherMain();
//        } else if(jsd.getType() == 1){
//            voucher = xxfpdrDao.findVoucherMain();
//        } else {
//            voucher = wlfpdrDao.findVoucherMain();
//        }
        return fpdrDao.findVoucherMain();
    }

    public List<Map> getVoucherItem(Long jsdId) {
        Jsd jsd = jsdService.findXsjsdDetail(jsdId);
        List<Map> list = new ArrayList<Map>();
        if (jsd.getType() == 0) {//采购
            list.addAll(jxfpdrDao.findVoucherItem(jsdId));
        } else if (jsd.getType() == 1) {//销售
            list.addAll(xxfpdrDao.findVoucherItem(jsdId));
        } else {//物流
            list.addAll(wlfpdrDao.findVoucherItem(jsdId));
        }
        return fpdrDao.getVoucherItems(jsd.getType(), jsdId, jsd);
    }

    @Transactional
    public void fpChangeDrrq(Long jsdId, Date date) {
        Jsd jsd = jsdService.findXsjsdDetail(jsdId);
        jsd.setDrrq(date);
        fpDao.save(jsd);
    }

    public Map getVoucher(Long jsdId, String uuid, Integer year, Integer mouth, Map voucherMaster) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Map<String, Object> result = new HashMap<String, Object>();
        Map master = findVoucherMain(jsdId);
        DecimalFormat df = new DecimalFormat("#.##");
        Jsd jsd = jsdService.findXsjsdDetail(jsdId);
        master.put("id", uuid);
        master.put("acctyear", voucherMaster.get("acctyear"));//会计年度
        master.put("acctperiod", voucherMaster.get("acctperiod"));//会计期间
        master.put("acctbookcode", "01");//账薄标识
        master.put("unitcode", jsd.getCggs() != null && jsd.getCggs().getJiuqiUnitCode() != null ? jsd.getCggs().getJiuqiUnitCode() : "");//组织机构代码
        master.put("attachment", voucherMaster.get("attachment"));//附件张数
        master.put("createdate", voucherMaster.get("createdate"));//附件张数
        master.put("memo", voucherMaster.get("bz"));//备注
        result.put("master", master);
        int order = 1;
        List<Map> items = getVoucherItem(jsdId);
        for (Map m : items) {
            m.put("id", order);//唯一标识
            m.put("vchrid", uuid);//凭证主表ID
            m.put("itemorder", order);//分录编号
            m.put("subjectcode", m.get("subjectcode") != null ? m.get("subjectcode") : "");//科目代码
            m.put("subjectname", m.get("subjectname") != null ? m.get("subjectname") : "");//科目名称
            m.put("debit", m.get("debit") != null ? df.format(m.get("debit")) : "0.00");//借方金额
            m.put("credit", m.get("credit") != null ? df.format(m.get("credit")) : "0.00");//贷方金额
            m.put("qty", m.get("qty") != null ? m.get("qty") : 0);//数量
            m.put("price", 0);//单价
            m.put("currencycode", "CNY");//货币代码
            m.put("exchrate", 1.000000);//汇率
            m.put("orgnd", m.get("debit") != null ? m.get("debit") : "0.00");//借方原币
            m.put("orgnc", m.get("credit") != null ? m.get("credit") : "0.00");//贷方原币
            m.put("settlementcode", "");//结算方式代码
            m.put("settlementno", "");//结算号
            m.put("bizdate", simple.format(new Date()));//业务日期
            m.put("digest", m.get("digest") != null ? m.get("digest") : "");//摘要
            m.put("bizno", "");//业务号
            m.put("suppliername", m.get("suppliername") != null ? m.get("suppliername") : "");//供应商名称
            m.put("suppliercode", m.get("suppliercode") != null ? m.get("suppliercode") : "");//供应商代码
            m.put("departmentname", m.get("departmentname") != null ? m.get("departmentname") : "");//部门名称
            m.put("departmentcode", m.get("departmentcode") != null ? m.get("departmentcode") : "");//部门代码
            m.put("customername", m.get("customername") != null ? m.get("customername") : "");//客户名称
            m.put("customercode", m.get("customercode") != null ? m.get("customercode") : "");//客户代码
            m.put("staffname", m.get("staffname") != null ? m.get("staffname") : "");//职员名称
            m.put("staffcode", m.get("staffcode") != null ? m.get("staffcode") : "");//职员代码
            order++;
        }
        result.put("items", items);
        return result;
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Jsd result = fpDao.get(id);
        if (result == null) {
            throw new RuntimeException("未获取凭证信息!");
        }
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode", result.getCggs().getJiuqiUnitCode());//单位代码
        revokeInfo.put("vchrtypecode", "记");//会计年度
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        revokeInfo.put("acctperiod", simpleDateFormat3.format(result.getDrrq()));//会计年度
        revokeInfo.put("vchrnum", result.getVoucherNum());//凭证号

        return revokeInfo;
    }

    public List<Jsd> findJsdHb(Long hbjsdId) {
        Jsdhb jsdhb = jsdhbDao.get(hbjsdId);
        return jsdhb.getJsdList();
    }

    @Transactional
    public String findAllfpdr(Integer type, Integer fpdrZt, String jsdh, Date sqrqStart, Date sqrqEnd, Long glqyId, String glqyQc, Long gsId, String gsJc, Long fpzlId, int pageNo, int pageSize) {
        if ("".equals(gsJc)) {
            gsId = null;
        }
        Page<Jsd> fpPage = this.fpDao.findfpdrList(type, fpdrZt, jsdh, sqrqStart, sqrqEnd, glqyId, glqyQc, gsId, gsJc, fpzlId, pageNo, pageSize);
        List<Jsd> fpList = fpPage.getResult() == null ? new ArrayList<Jsd>() : fpPage.getResult();
        if (fpList.size() > 0) {
            fpList = getCzztByJsd(fpList);
        }
        String fpJson = BaseUtils.fetchCollectionToJson(fpList, "id", "jsdh", "sqrq", "glqy.qyfr.nsh", "type", "glqy.id", "glqy.qc", "fpze", "ddfy", "fpzl", "hm", "sqr.id", "sqr.xm", "gs.id", "gs.jc", "cggs.id", "cggs.jc", "insertFlag", "kprq", "kpr.id", "kpr.xm", "czzt", "voucherNum");
        return "{\"total\":" + fpPage.getTotalCount() + ",\"rows\":[" + fpJson + "]}";
    }


    public List<Jsd> getCzztByJsd(List<Jsd> jsdList) {
        for (Jsd p : jsdList) {
            String czzt = "";
            if (p.getInsertFlag() == 1 && p.getDeleteFlag() == 1) {
                czzt = "wdr";
            } else if (p.getInsertFlag() == 1 && p.getDeleteFlag() == 3) {
                czzt = "sccg";
            } else if (p.getInsertFlag() == 3 && p.getDeleteFlag() == 1) {
                czzt = "drcg";
            } else if (p.getInsertFlag() == 2 && p.getDeleteFlag() == 1 || p.getInsertFlag() == 2 && p.getDeleteFlag() == 3) {
                czzt = "drsb";
            } else if (p.getInsertFlag() == 3 && p.getDeleteFlag() == 2) {
                czzt = "scsb";
            } else {
                czzt = "null";
            }
            p.setCzzt(czzt);
        }
        return jsdList;
    }


    /**
     * 查询收款审核明细
     *
     * @param id
     * @return
     */
    @Transactional
    public Jsd findfpDetail(Long id) {
        return this.fpDao.get(id);
    }

    /**
     * 审核状态
     *
     * @param id
     * @param status
     */
    @Transactional
    public void changeStatus(Long id, Integer status) {
        Jsd fp = this.findfpDetail(id);
        Yg kpr = YgService.getCurrentYg();
        fp.setKpr(kpr);
        fp.setKprq(new Date());
        fp.setShzt(1);
        this.fpDao.save(fp);
    }

    @Transactional
    public void fpdrCombine(String jsdIdList) {
        String[] result = jsdIdList.split(",");
        List<Jsd> jsds = new ArrayList<Jsd>();
        for (int i = 0; i < result.length; i++) {
            Jsd j = new Jsd();
            j = jsdService.findXsjsdDetail(Long.parseLong(result[i]));
            jsds.add(j);
        }
        Gsjg gs = jsds.get(0).getGs();
        for (Jsd m : jsds) {
            if (m.getGs() != gs) {
                throw new RuntimeException("公司必须一致");
            }
        }
        Jsdhb jsdhb = new Jsdhb();
        jsdhb.setJsdList(jsds);
        jsdhb.setGs(gs);
        jsdhb.setHbr(YgService.getCurrentYg());
        jsdhb.setKjqj(0);
        jsdhb.setHbrq(new Date());
        jsdhb.setHbdh(this.getNextFpPxh() + 1);
        jsdhb.setCreateUser(YgService.getCurrentYg());
        jsdhb.setCreateOrgan(YgService.getCurrentYg().getZggs());
        jsdhb.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        jsdhbDao.save(jsdhb);
    }

    public Integer getNextFpPxh() {
        return jsdhbDao.getMaxfpPxh() == null ? 0 : jsdhbDao.getMaxfpPxh();
    }

    /**
     * 获取U8凭证分录信息
     *
     * @param jsdId
     * @param uuid
     * @return
     */
    @Transactional
    public Map getU8VoucherItems(Long jsdId, String uuid, List<VoucherItemData> voucherItemDataList, Date documentDate) {

        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate = simple.format(new Date());
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map> list = getVoucherItem(jsdId);
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for (Map m : list) {
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            //voucherItem.put("id", order);//唯一标识
            //voucherItem.put("vchrid", uuid);//凭证主表ID
            voucherItem.put("entry_id", order);//分录编号
            voucherItem.put("account_code", m.get("subjectcode") != null ? m.get("subjectcode") : "");//科目代码
//                voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
            voucherItem.put("natural_debit_currency", m.get("debit") != null ? df.format(m.get("debit")) : "0.00");//借方金额
            voucherItem.put("natural_credit_currency", m.get("credit") != null ? df.format(m.get("credit")) : "0.00");//贷方金额
//                voucherItem.put("qty", item.getSl() != null ? item.getSl() : 0);//数量
            voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
            voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
            voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
            voucherItem.put("currency", "CNY");//货币代码
            voucherItem.put("exchange_rate2", "1.000000");//汇率
//                voucherItem.put("orgnd", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方原币
//                voucherItem.put("orgnc", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方原币
            voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
            voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
            voucherItem.put("document_date", systemDate);//票据日期，在科目是银行或往来时，可以填写此项
            voucherItem.put("abstract", m.get("digest") != null ? m.get("digest") : "");//摘要
//                voucherItem.put("bizno", "");//业务号
            Map<String, String> fzhsMap = new HashMap<String, String>();
            Map<String, String> xjllxmMap = new HashMap<String, String>();
            fzhsMap = this.findFzhsByMap(m, fzhsMap);
            voucherItem.put("auxiliary_accounting", fzhsMap);
            voucherItem.put("cash_flow", xjllxmMap);
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    private Map<String, String> findFzhsByMap(Map<Object, String> map, Map<String, String> fzhsMap) {
        if (map.get("customercode") != null && !map.get("customercode").toString().equals("")) {
            fzhsMap.put("cust_id", map.get("customercode"));
//            fzhsMap.put("operator","-");
        }
        if (map.get("suppliercode") != null && !map.get("suppliercode").toString().equals("")) {
            fzhsMap.put("supplier_id", map.get("suppliercode"));
            fzhsMap.put("operator", "-");
        }
        return fzhsMap;
    }


    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate = simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        Jsd fp = this.fpDao.get(id);
        voucherMaster.put("id", uuid);
//        if(cwsf.getPjlx().getZ().equals("银票") || cwsf.getPjlx().getZ().equals("商票") || cwsf.getPjlx().getZ().equals("信用证") && cwsf.getKxlx()==1){
//            voucherMaster.put("vchrtypecode", "转账");//凭证类别
//        }else{
        voucherMaster.put("vchrtypecode", "记");//凭证类别
//        }
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        voucherMaster.put("unitcode", fp.getCggs() != null && fp.getCggs().getJiuqiUnitCode() != null ? fp.getCggs().getJiuqiUnitCode() : "");//组织机构代码
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getXm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        voucherMaster.put("companyId", fp.getCggs().getId());//公司ID
        return voucherMaster;
    }


    //========================setter==========================
    @Autowired
    public void setFpDao(FpDao fpDao) {
        this.fpDao = fpDao;
    }

    @Autowired
    public void setJsdService(XsjsdService jsdService) {
        this.jsdService = jsdService;
    }

    @Autowired
    public void setJsdhbDao(JsdhbDao jsdhbDao) {
        this.jsdhbDao = jsdhbDao;
    }

    @Autowired
    public void setFpdrDao(FpdrDao fpdrDao) {
        this.fpdrDao = fpdrDao;
    }

    @Autowired
    public void setJxfpdrDao(JxfpdrDao jxfpdrDao) {
        this.jxfpdrDao = jxfpdrDao;
    }

    @Autowired
    public void setXxfpdrDao(XxfpdrDao xxfpdrDao) {
        this.xxfpdrDao = xxfpdrDao;
    }

    @Autowired
    public void setWlfpdrDao(WlfpdrDao wlfpdrDao) {
        this.wlfpdrDao = wlfpdrDao;
    }
}
